package cn.wolfcode.luowowo.website.util;

import cn.wolfcode.luowowo.cache.util.RedisKeys;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * 添加cookie
     * @param name
     * @param value
     * @return
     */
    public static void setCookie(String name, String value, int time, HttpServletResponse response){
        Cookie cookie = new Cookie(name,value);
        cookie.setMaxAge(time);
        cookie.setPath("/");
        response.addCookie(cookie);
    }


    /**
     * 获取cookie中的token值
     * @param request
     * @param response
     * @return
     */
    public static String getToken(HttpServletResponse response, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        String token = null;
        if(cookies != null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token = cookie.getValue();
                    cookie.setMaxAge(RedisKeys.USER_LOGIN_TOKEN.getTime().intValue());
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return token;
    }

}
